import React, { Component } from 'react';
import {
  AppRegistry,
  StyleSheet,
  Text,
  View,
  Image,
  FlatList,
  RefreshControl,
  TouchableOpacity,
} from 'react-native';
import GitHubTrending from 'GitHubTrending'
import DataRepository, { FLAG_STORAGE } from '../expand/dao/DataRepository'
import LanguageDao, { FLAG_LANGUAGE } from '../expand/dao/LanguageDao'
import ScrollableTabView, { ScrollableTabBar } from 'react-native-scrollable-tab-view';
import TrendingRepoCell from '../common/TrendingRepoCell'
import ViewUtils from '../util/ViewUtils'
import ProjectModel from '../model/ProjectModel';
import Utils from '../util/Utils'
import FavoriteDao from '../expand/dao/FavoriteDao'

const URL = 'https://github.com/trending/';
var dataRepository = new DataRepository(FLAG_STORAGE.flag_trending);
var favoriteDao = new FavoriteDao(FLAG_STORAGE.flag_trending);
export default class TrendingPage extends Component {
  static navigationOptions = ({ navigation }) => ({
    headerTitle: '热门',
    tabBarLabel: '热门',
    headerRight: ViewUtils.getRightButton(() => { navigation.state.params.onMenu() }),
    headerStyle: { backgroundColor: '#2196F3' },
    headerTitleStyle: { alignSelf: 'center', color: 'white' },
    tabBarIcon: ({ tintColor }) => (
      <Image
        source={require('../../res/images/ic_polular.png')}
        style={[styles.icon, { tintColor: '#ffffff' }]}
      />
    ),
  });

  constructor(props) {
    super(props);
    dataRepository = new DataRepository(FLAG_STORAGE.flag_trending);
    this.languageData = new LanguageDao(FLAG_LANGUAGE.flag_language);
  }

  state = {
    delay: false,
    languages: [],
    result: ''
  }

  // 需要延迟加载 ScrollableTabView
  componentDidMount() {
    this.loadData();
    this.timer = setTimeout(() => {
      this.setState({
        delay: true
      });
    }, 100);
    this.props.navigation.setParams({
      onMenu: this.onMenu,
    })
  }

  onMenu() {
    console.log('onMenu');
  }

  renderTitleView() {
    return <View >
      <TouchableOpacity
        ref='button'
        underlayColor='transparent'
        onPress={() => this.showPopover()}>
        <View style={{ flexDirection: 'row', alignItems: 'center' }}>
          <Text style={{
            fontSize: 18,
            color: '#FFFFFF',
            fontWeight: '400'
          }}>趋势 {this.state.timeSpan.showText}</Text>
          <Image
            style={{ width: 12, height: 12, marginLeft: 5 }}
            source={require('../../res/images/ic_spinner_triangle.png')}
          />
        </View>
      </TouchableOpacity>
    </View>
  }

  loadData() {
    this.languageData.fetch()
      .then(result => {
        this.setState({
          languages: result,
        })
        console.log(this.state.languages);
      })
      .catch(error => {
        console.log(error);
      })
  }

  render() {
    let content = this.state.languages.length > 0 ?
      <ScrollableTabView style={styles.container}
        tabBarBackgroundColor="#2196F3"
        tabBarInactiveTextColor="mintcream"
        tabBarBackgroundColor="#2196F3"
        tabBarUnderlineStyle={{ backgroundColor: '#e7e7e7', height: 2 }}
        locked={false}
        renderTabBar={() => <ScrollableTabBar />}>
        {
          this.state.languages.map((result, i, arr) => {
            let lan = arr[i];
            return lan.checked ? <TrendingTab key={i} tabLabel={lan.name} {...this.props}></TrendingTab> : null;
          })
        }
      </ScrollableTabView> : <Text>数据为空</Text>;
    if (this.state.delay) {
      return <View style={styles.container}>
        {content}
      </View>
    } else {
      return <View>
        <Text>正在加载......</Text>
      </View>;
    }
  }
}

class TrendingTab extends Component {
  constructor(props) {
    super(props);
  }

  // 加载数据
  componentDidMount() {
    this.loadData();
  }

  state = {
    data: '',
    isLoading: true,
    favoriteKeys: [],
  }

  /**
   * 更新Project Item Favorite 状态
   */
  flushFavoriteState() {
    let projectModels = [];
    let items = this.items;
    for (var i = 0, len = items.length; i < len; i++) {
      // 把数据变成ProjectModel对象
      // 检测items[i] 是否存在收藏
      projectModels.push(new ProjectModel(items[i], Utils.checkFavorite(items[i], this.state.favoriteKeys)))
    }
    this.setState({
      isLoading: false,
      data: projectModels
    })
  }

  /**
   * 获取存储的收藏列表
   */
  getFavoriteKeys() {
    favoriteDao.getFavoriteKeys()
      .then(keys => {
        if (keys) {
          this.setState({ favoriteKeys: keys })
        }
        this.flushFavoriteState();
      })
      .catch(e => {
        this.flushFavoriteState();
      })
  }

  /**
   * 网络请求
   */
  loadData() {
    let url = `${URL}${this.props.tabLabel}`
    dataRepository
      .fetchRepository(url)
      .then(result => {
        this.items = result && result.items ? result.items : result ? result : [];
        // this.setState({
        //   data: items,
        //   isLoading: false,
        // });
        this.getFavoriteKeys();
        // 如果数据缓存过期了，则重新获取网络数据
        if (result && result.update_date && !dataRepository.checkData(result.update_date)) {
          return dataRepository.fetchNetRepository(url);
        }
      })
      .then(items => {
        // 如果数据没更新就不刷新数据
        if (!items || items.length === 0) return;
        this.items = items;
        this.getFavoriteKeys();
      })
      .catch(error => {
        this.setState({
          isLoading: false,
        })
      })
  }

  // 跳转详情页
  onSelect(projectModel) {
    this.props.navigation.navigate('RepositoryDetail', {
      title: projectModel.item.fullName,
    });
  }


  /**
   * favoriteIcon的单击回调函数
   * @param {*} item 每一项 
   * @param {*} isFavorite 是否收藏 
   */
  onFavorite(item, isFavorite) {
    if (isFavorite) {
      favoriteDao.saveFavoriteItem(item.fullName, JSON.stringify(item));
    } else {
      favoriteDao.removeFavoriteItem(item.fullName);
    }
  }
  renderItem(item) {
    return <TrendingRepoCell
      projectModel={item}
      onSelect={() => this.onSelect(item)}
      onFavorite={(item, isFavorite) => this.onFavorite(item, isFavorite)}
    />
  }

  render() {
    return (
      <View style={styles.container}>
        <FlatList
          data={this.state.data}
          renderItem={({ item }) => this.renderItem(item)}
          // 用index作为key
          keyExtractor={(item, index) => index}
          refreshControl={
            <RefreshControl
              refreshing={this.state.isLoading}
              // 重新刷新
              onRefresh={() => this.loadData()}
              // 刷新图片颜色
              colors={['#2196F3']}
              tintColor={'#2196F3'}
              title={'Loading......'}
            />
          }
        />
      </View>
    )
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#F5FCFF',
  },
  text: {
    fontSize: 22
  },
  icon: {
    height: 22,
    width: 22,
  },
  loading: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center'
  },
})
